const util = require('../../../utils/util.js');
const api = require('../../../config/api.js');
const moment = require('../../../lib/moment/moment.min.js');
var QQMapWX = require('../../../lib/qqmap-wx-jssdk.min.js');
var qqmapsdk;
var app = getApp();
var page = [];
var that;
Page({
  data: {
    scrollTop: 0,
    cityCode:'',
    tabs: [],
    tabIndex: 0,
    pageContents:[],
    isLoads:[],
    curHostRes: api.curHostRes,
    isRefresh:false,
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    that = this;
    if (options.isRefresh){
      that.setData({ isRefresh:true});
    }
    var index = that.data.tabIndex;
    if (page[index]){
      page[index].reset();
    }
    that._loadTabs();
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'BJFBZ-ZFTHW-Y2HRO-RL2UZ-M6EC3-GMF4U'
    });
  },
  _loadTabs(){
    app.post(api.GetArticleCategory,{retry:3, isAllow:true}).then(rsp => {
      if(rsp.data && Object.keys(rsp.data).length>0){
        rsp.data.forEach(function(i,n){
          that.data.tabs.push({
            text: i.title, id:i.id, active: false
          });
          that.data.isLoads.push(false);
          page.push(util.page.clone());
          that.data.pageContents.push({ data: [], scrollTop:0})
        });
        that.data.tabs[0].active = true;
        that.setData({
          tabs: that.data.tabs,
          isLoads:that.data.isLoads,
          pageContents: that.data.pageContents
        });
        that.loadArticles();
      }
    }).catch((err) => {
      console.log(err);
    });
  },
  loadArticles: function () {
    let index = that.data.tabIndex;
    let params = { article_cate_id: that.data.tabs[index].id, isAllow: true};
    //资讯加载社区数据时添加当前市编码
    if (index == 1){
      params.cityCode = that.data.cityCode;
    }
    //数据处理
    var handleData = that.data.pageContents[index];
    app.loadPageExt(api.GetArticles, page[index], params).then(rsp => {
      if (rsp && rsp.length>0) {
        rsp.forEach(function (i, n) {
          i.showCreateTime = moment(i.update_time*1000).format('YYYY-M-DD');
          //api.curHost.substr(0, api.curHost.lastIndexOf('.com') + 4) 
          i.logo = '../'+ i.logo;
          handleData.data.push(i);
        });
        that.data.isLoads[index] = true;
        that.setData({
          'pageContents': that.data.pageContents,
          'isLoads': that.data.isLoads
        });
        //console.log('pageContents', that.data.pageContents);
      }
    }).catch((err) => {
      console.log(err);
    });
  },
  goToDetail(e){
    var id = e.currentTarget.id;
    wx.navigateTo({
      url: '../detail/detail?id='+id,
    })
  },
  share(){},
  onPullDownRefresh() {
    var index = that.data.tabIndex;
    page[index].reset();
    that.data.pageContents[index] = { data: [], scrollTop:0};
    that.setData({
      'pageContents': that.data.pageContents
    });
    that.loadArticles();
    wx.stopPullDownRefresh();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  },
  scroll(e) {
    let index = that.data.tabIndex;
    that.data.pageContents[index].scrollTop = e.detail.scrollTop;
  },
  lower(e){
    that.loadArticles();
  },
  onReady: function () { },
  onShow: function () {
    if (that.data.isRefresh){
      that.onPullDownRefresh();
      that.setData({isRefresh:false});
    }
  },
  commonTab: function (index) {
    this.data.tabs.forEach(function (n, i) {
      if (index == i) {
        n.active = true;
      } else {
        n.active = false;
      }
    });
    this.setData({ tabs: this.data.tabs, tabIndex: index});
  },
  selTab: function (e) {
    let index = e.currentTarget.dataset.index;
    this.commonTab(index);
  },
  tabChange: function (e) {
    let index = e.detail.current;
    this.commonTab(index);
    if (!that.data.isLoads[index]) {
      page[index].reset();
      if (that.data.cityCode == '' && index == 1){
        that.authLocation().then(rsp => {
          that.loadArticles();
        }).catch(err => {
          console.log(err);
        });
      }else{
        that.loadArticles();
      }
    }
  },
  onShareAppMessage: function (ops) {
    var sharerId = 1, article;
    if (ops.from === 'button') {
      var index = ops.target.dataset.id;
      // 来自页面内转发按钮
      var pageContents = that.data.pageContents[that.data.tabIndex];
      article = pageContents.data[index];
      return {
        title: article.title,
        path: 'pages/info/detail/detail?id='+ article.id,
        imageUrl: that.data.curHostRes+article.logo
      }
    } else {
      return {
        title: '营销推广',
        path: 'pages/info/list/list?isRefresh=true'
      }
    }
  },
  poiAddr(latitude, longitude) {
    return new Promise(function (resolve, reject) {
      qqmapsdk.reverseGeocoder({
        location: {
          latitude: latitude,
          longitude: longitude
        },
        success: function (ress) {
          //console.log('ress', ress)
          ////adcode:"350211"city:"厦门市"city_code:"156350200"district:"集美区"
          var ad_info = ress.result.ad_info;
          //区县编码
          that.data.districtCode = ad_info.adcode;
          that.data.districtName = ad_info.district;
          //城市编码
          var cityCode = ad_info.city_code.replace(ad_info.nation_code, "");
          that.data.cityCode = cityCode.replace(/^(\d+)(\d{2})$/, '$1');
          that.data.city = ad_info.city;
          //省编码
          that.data.provCode = cityCode.replace(/(\d{2})\d*/, '$1');
          that.data.provName = ad_info.province;
          resolve(ress);
        }
      });
    });
  },
  authLocation() {
    return new Promise(function (resolve, reject) {
      wx.getSetting({
        success: (res) => {
          if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
            wx.showModal({
              title: '是否授权当前位置',
              content: '需要获取您的地理位置，请确认授权',
              success: function (res) {
                if (res.cancel) {
                  reject("授权失败返回数据");
                } else if (res.confirm) {
                  wx.openSetting({
                    success: function (data) {
                      if (data.authSetting["scope.userLocation"] == true) {
                        util.toast.success('授权成功');
                        wx.getLocation({
                          type: 'wgs84',
                          success: function (res) {
                            var latitude = res.latitude
                            var longitude = res.longitude
                            resolve(that.poiAddr(latitude, longitude));
                          },
                          fail(res) {
                            reject("授权失败");
                          }
                        })
                      } else {
                        reject("授权失败");
                      }
                    }
                  })
                }
              }
            })
          } else {
            wx.getLocation({
              type: 'wgs84',
              success: function (res) {
                var latitude = res.latitude
                var longitude = res.longitude
                resolve(that.poiAddr(latitude, longitude));
              },
              fail(res) {
                reject("授权失败");
              }
            })
          }
        }
      })
    });
  },
})